<?php

declare(strict_types=1);

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;

if (isset($app)) {
    $beforeMiddleware = function (ServerRequestInterface $request, RequestHandlerInterface $handler) use ($app) {
        // Example: Check for a specific header before proceeding
        $auth = $request->getHeaderLine('Authorization');
        if (!$auth) {
            // Short-circuit and return a response immediately
            $response = $app->getResponseFactory()->createResponse();
            $response->getBody()->write('Unauthorized');

            return $response->withStatus(401);
        }

        // Proceed with the next middleware
        return $handler->handle($request);
    };

    $afterMiddleware = function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
        // Proceed with the next middleware
        $response = $handler->handle($request);

        // Modify the response after the application has processed the request
        $response = $response->withHeader('X-Added-Header', 'some-value');

        return $response;
    };

    $app->add($afterMiddleware);
    $app->add($beforeMiddleware);

    $app->get('/', function (ServerRequestInterface $request, ResponseInterface $response, array $args) {
        $data = json_encode(['success' => 'ok']);
        $response->getBody()->write($data);
        return $response;
    });
}